package com.apps.gomdiem.fragment;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.apps.gomdiem.R;
import com.apps.gomdiem.activity.AddStore;
import com.apps.gomdiem.activity.ChangePointActivity;
import com.apps.gomdiem.activity.EditInfoActivity;
import com.apps.gomdiem.activity.EditPassActivity;
import com.apps.gomdiem.activity.HistoryChangePoint;
import com.apps.gomdiem.activity.RegisterActivity;
import com.apps.gomdiem.helper.DataBaseHelper;
import com.apps.gomdiem.model.UserAccount;
import com.apps.gomdiem.model.UserAccount.ProfileItem;
import com.apps.gomdiem.view.InputRequirement;

public class ProfileTabFragment extends Fragment implements OnClickListener {
	private static final String TAG = "ProfileTabFragment";
//	String mUsername;
//	String mPassword;
//	String mName;
//	String mAddress;
//	String mEmail;
//	String mPhone;
//	private TextView txtShowName;
//	private TextView txtShowUsername;
//	private TextView txtShowPassword;
//	private TextView txtShowAddress;
//	private TextView txtShowEmail;
//	private TextView txtShowPhone;
//	private Button btnChangePoint, btnHistory, btnEditPass, btnEditInfo, btnManageStore;
//	private Button btnEditPassword, btnEditAddress, btnEditEmail, btnEditPhone;
	private ViewGroup parent;
	private InputRequirement required = new InputRequirement();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null)
			return null;
		parent = (ViewGroup) inflater.inflate(R.layout.profile_activity, container, false);
		return parent;
	}

	public void onStart() {
		super.onStart();
		UserAccount user = UserAccount.getInstance(getActivity());
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
		String username = settings.getString(UserAccount.TAG, null);
		genScreen(username == null || username.equals(user.mUserName));
		setActionForAllButtons(parent);
		required.setBlankErrorMsg(getString(R.string.error_blank));
	}

	private void setActionForAllButtons(ViewGroup parent) {
		int childrentCount = parent.getChildCount();
		if (childrentCount == 0) {
			Log.d(TAG, "There is no view in this group");
			return;
		}
		for (int i = 0; i < childrentCount; i++) {
			View v = parent.getChildAt(i);
			if (v instanceof ViewGroup)
				setActionForAllButtons((ViewGroup) v);
			else if (v instanceof Button)
				((Button) v).setOnClickListener(this);
		}
	}

	// Save data to device
	private void onLoginSuccess(UserAccount user) {
		Activity app = getActivity();
		Editor edit = PreferenceManager.getDefaultSharedPreferences(app).edit();
		edit.putString(UserAccount.TAG, user.mUserName);
		edit.commit();

		try {
			getActivity().deleteFile(UserAccount.TAG);
			FileOutputStream fos = app.openFileOutput(UserAccount.TAG, Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(user);
			oos.flush();
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private void genScreen(boolean isLoginScreen) {
		Editor settings = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
		if (isLoginScreen) {
			parent.findViewById(R.id.login_screen).setVisibility(View.VISIBLE);
			parent.findViewById(R.id.profile_screen).setVisibility(View.GONE);

			settings.remove(UserAccount.TAG).commit();
			return;
		}

		// Show profile screen
		parent.findViewById(R.id.login_screen).setVisibility(View.GONE);
		parent.findViewById(R.id.profile_screen).setVisibility(View.VISIBLE);
		UserAccount user = UserAccount.getInstance(getActivity());
		ListView list = (ListView) parent.findViewById(R.id.profiles);
		list.setAdapter(new ProfileAdapter(getActivity(), user.genInfo()));
	}

	@Override
	public void onClick(View v) {
		Intent action = null;
		Activity app = getActivity();
		switch (v.getId()) {
		case R.id.btnChangePoint:
			Intent intent = new Intent(getActivity(), ChangePointActivity.class);
			startActivity(intent);
			break;
		case R.id.btnHistory:
			Intent intent1 = new Intent(getActivity(), HistoryChangePoint.class);
			startActivity(intent1);
			break;
		case R.id.btnEditInfo:
			Intent intent2 = new Intent(getActivity(), EditInfoActivity.class);
			startActivity(intent2);
			break;
		case R.id.btnEditPass:
			Intent intent3 = new Intent(getActivity(), EditPassActivity.class);
			startActivity(intent3);
			break;
		case R.id.btnLogin:
			if (!required.acceptRequirements())
				return;
			EditText edtUsername = (EditText) getActivity().findViewById(R.id.username);
			EditText edtPwd = (EditText) getActivity().findViewById(R.id.password);
			String username = edtUsername.getText().toString();
			try {
				Double.parseDouble(username);
			} catch (NumberFormatException e) {
				Log.d(TAG, "Input is e-mail!");
				if (!Pattern.matches(InputRequirement.MAIL_PATTERN, username)) {
					edtUsername.setError(getString(R.string.error_email));
					return;
				}
			}
			DataBaseHelper db = new DataBaseHelper(getActivity());
			db.getReadableDatabase();
			UserAccount user = db.getUserAccount(username, edtPwd.getText().toString());
			break;
		case R.id.btnReg:
			action = new Intent(getActivity(), RegisterActivity.class);
			break;
		case R.id.btnManageStore:
			Intent intent5 = new Intent(getActivity(), AddStore.class);
			startActivity(intent5);
		case R.id.btnEdit:
			break;
		case R.id.btnLogout:
			break;
		}
		if (action != null)
			startActivity(action);
	}

	private static class ProfileAdapter extends ArrayAdapter<ProfileItem> {

		public ProfileAdapter(Context context, List<ProfileItem> objects) {
			super(context, R.layout.profile_item, objects);
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			ViewHolder holder;
			if (v == null) {
				v = LayoutInflater.from(getContext()).inflate(R.layout.profile_item, null);
				holder = new ViewHolder();
				holder.title = (TextView) v.findViewById(R.id.title);
				holder.val = (TextView) v.findViewById(R.id.value);
				v.setTag(holder);
			} else
				holder = (ViewHolder) v.getTag();

			ProfileItem item = getItem(position);
			holder.title.setText(item.titleId);
			holder.val.setText(item.value);
			return v;
		}
	}

	private static class ViewHolder {
		public TextView title;
		public TextView val;
	}
}